package com.management.demo.controller.wx;

import cn.dev33.satoken.util.SaResult;
import com.management.demo.dto.wx.UserPointDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

@Tag(name = "微信用户积分接口")
@RestController
@RequestMapping("wx/user/point")
public class WXUserPointController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private final String POINT_KEY = "user:point";

    @Operation(summary = "根据id获取用户积分信息")
    @GetMapping("get/{id}")
    public SaResult getById(@Parameter(description = "用户id")
                                      @PathVariable Integer id) {
        BigDecimal point = BigDecimal.ZERO;
        Double score = stringRedisTemplate.opsForZSet().score(POINT_KEY, String.valueOf(id));
        if (score != null) {
            point = BigDecimal.valueOf(score);
        }
        return SaResult.ok().setData(point);
    }

    @Operation(summary = "给用户添加/减少积分")
    @PostMapping("addOrReduce")
    public SaResult createOrEdit(@RequestBody UserPointDTO userPointDTO) {
        Integer id = userPointDTO.getId();
        BigDecimal point = userPointDTO.getPoint();
        stringRedisTemplate.opsForZSet().incrementScore(POINT_KEY, String.valueOf(id), point.doubleValue());
        return SaResult.ok().setData(true);
    }
}
